package com.cuitrip.business.tripservice;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.NinePatchDrawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.cuitrip.app.base.PaddingItemDecoration;
import com.cuitrip.business.tripservice.event.ServiceChangeEvent;
import com.cuitrip.business.tripservice.model.FormType;
import com.cuitrip.business.tripservice.model.PictureDescription;
import com.cuitrip.business.tripservice.model.ServiceInfo;
import com.cuitrip.business.tripservice.presenter.TripEditPicPresenter;
import com.cuitrip.business.tripservice.ui.TripEditPicView;
import com.cuitrip.business.tripservice.ui.UploadDialog;
import com.cuitrip.service.R;
import com.h6ah4i.android.widget.advrecyclerview.draggable.RecyclerViewDragDropManager;
import com.h6ah4i.android.widget.advrecyclerview.utils.WrapperAdapterUtils;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragment;
import com.lab.component.list.CTRecyclerView;
import com.lab.component.list.simple.CTSimpleRecyclerAdapter;
import com.lab.component.list.simple.CTSimpleViewHolder;
import com.lab.rx.bus.RxBus;
import com.lab.utils.ArrayUtil;
import com.lab.utils.DisplayUtil;
import com.lab.utils.ImageHelper;
import com.lab.widget.imageselector.MultiImageSelectorActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created ak
 */
public class TripEditPicFragment extends CustomUiFragment implements TripEditPicView {


    public static final String KEY_PIC_LIST = "key_pic_list";

    public static final int REQUEST_PICTURE_LIST = 0x01;
    public static final int REQUEST_IMAGE_SELECT = 0x02;

    @Bind(R.id.ct_recycler_view)
    CTRecyclerView mCtRecyclerView;
    @Bind(R.id.submit)
    TextView mSubmit;
    private View mContentView;
    private CTSimpleRecyclerAdapter mAdapter;
    private ArrayList<PictureDescription> mPictureDescriptionList = new ArrayList<>();

    private TripEditPicPresenter mTripEditPicPresenter;
    private RecyclerView.Adapter mWrappedAdapter;
    private RecyclerViewDragDropManager mRecyclerViewDragDropManager;

    private ServiceInfo mServiceInfo;
    private UploadDialog uploadingDialog;

    public static TripEditPicFragment getInstance(ServiceInfo serviceInfo, ArrayList<String> needUploadList) {
        TripEditPicFragment fragment = new TripEditPicFragment();
        Bundle bundle = new Bundle();
        if (!ArrayUtil.isNullOrEmpty(needUploadList)) {
            bundle.putSerializable(KEY_PIC_LIST, needUploadList);
        }
        bundle.putSerializable(ServiceInfo.KEY, serviceInfo);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContentView = super.onCreateView(inflater, container, savedInstanceState, R.layout.ct_page_image_list);
        ButterKnife.bind(this, mContentView);
        return mContentView;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        mTripEditPicPresenter = new TripEditPicPresenter();
        mTripEditPicPresenter.attachView(this);
        Bundle bundle = getArguments();
        if (null != bundle) {
            mServiceInfo = (ServiceInfo) bundle.getSerializable(ServiceInfo.KEY);
            if (bundle.containsKey(KEY_PIC_LIST)) {
                List<String> mFilePathList = bundle.getStringArrayList(KEY_PIC_LIST);
                mTripEditPicPresenter.appendUploadList(mFilePathList);
            }
            mTripEditPicPresenter.initServiceInfo(mServiceInfo);
        }
        inflateList();
        super.onCreate(savedInstanceState);
    }

    private void inflateList() {
        mPictureDescriptionList = mServiceInfo.getPictureDescriptionList();
    }


    @Override
    public void initView() {
        ButterKnife.bind(this, mContentView);
        GridLayoutManager mgr = new GridLayoutManager(getHostActivity(), 3);
        mCtRecyclerView.setLayoutManager(mgr);
        mAdapter = new CTSimpleRecyclerAdapter<PictureDescription>(getHostActivity(), mPictureDescriptionList) {
            @Override
            public int getItemLayoutId(int viewType) {
                return R.layout.ct_layout_trip_image_item;
            }

            @Override
            public void onNewViewHolder(CTSimpleViewHolder viewHolder, ViewGroup parent, int viewType) {
            }

            @Override
            public void bindData(CTSimpleViewHolder holder, final int position, final PictureDescription item) {
                final ImageView imageView = holder.getView(R.id.trip_image);
                final View tagView = holder.getView(R.id.tag_view);
                if (position == 0) {
                    tagView.setVisibility(View.VISIBLE);
                } else {
                    tagView.setVisibility(View.INVISIBLE);
                }
                if (!mRecyclerViewDragDropManager.isDragging()) {
                    ImageHelper.displayCtImage(item.getUrl(), imageView, null);
                }
                holder.getView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PictureListActivity.launchPictureView(TripEditPicFragment.this, mPictureDescriptionList, position, true, REQUEST_PICTURE_LIST);
                    }
                });

            }

            @Override
            public boolean onCheckCanStartDrag(CTSimpleViewHolder holder, int position, int x, int y) {
                return true;
            }
        };

        mAdapter.setHasStableIds(true);

        //drag and drop manager
        mRecyclerViewDragDropManager = new RecyclerViewDragDropManager();
        mRecyclerViewDragDropManager.setDraggingItemShadowDrawable(
                (NinePatchDrawable) ContextCompat.getDrawable(getContext(), R.drawable.material_shadow_z3));
        // Start dragging after long press
        mRecyclerViewDragDropManager.setInitiateOnLongPress(true);
        mRecyclerViewDragDropManager.setInitiateOnMove(false);
        mRecyclerViewDragDropManager.setLongPressTimeout(750);


        mWrappedAdapter = mRecyclerViewDragDropManager.createWrappedAdapter(mAdapter);

        mCtRecyclerView.addItemDecoration(new PaddingItemDecoration(0, DisplayUtil.dip2px(8), DisplayUtil.dip2px(8), 0));
        mCtRecyclerView.setAdapter(mWrappedAdapter);

        mCtRecyclerView.setItemAnimator(null);
        mRecyclerViewDragDropManager.attachRecyclerView(mCtRecyclerView.getRecyclerView());
    }

    @Override
    public void onPause() {
        mRecyclerViewDragDropManager.cancelDrag();
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        if (mRecyclerViewDragDropManager != null) {
            mRecyclerViewDragDropManager.release();
            mRecyclerViewDragDropManager = null;
        }

        if (mCtRecyclerView != null) {
            mCtRecyclerView.setItemAnimator(null);
            mCtRecyclerView.setAdapter(null);
            mCtRecyclerView = null;
        }

        if (mWrappedAdapter != null) {
            WrapperAdapterUtils.releaseAll(mWrappedAdapter);
            mWrappedAdapter = null;
        }
        mAdapter = null;
        ButterKnife.unbind(this);
        super.onDestroyView();
    }

    @Override
    public void initData() {
        mTripEditPicPresenter.uploadPicList();
    }


    public void initListener() {
    }


    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        config.mTopbarMiddleAreaName = getString(R.string.trip_photo_operate_choose);
        config.mRightStyle = CustomUiConfig.AreaStyle.ICON_STYLE;
        return config;
    }

    @OnClick(R.id.submit)
    public void addPhoto() {
        mTripEditPicPresenter.addPhoto(this, REQUEST_IMAGE_SELECT);
    }

    @Override
    public void showLoadingDialog() {
        showLoading();
    }


    public void showUploading(int index, int total, int progress) {
        if (uploadingDialog == null ) {
            uploadingDialog = UploadDialog.getInstance();
            uploadingDialog.setCancelCallback(new UploadDialog.DialogCancelCallback() {
                @Override
                public boolean onCancelClick() {
                    mTripEditPicPresenter.cancelUpload();
                    return false;
                }
            });
        }
        uploadingDialog.setProgressInTotal(index, total);
        uploadingDialog.setProgress(progress);
        if (!uploadingDialog.isAdded() && !uploadingDialog.isShowing()) {
            showDialogFragment(uploadingDialog);
            uploadingDialog.setCancelable(false);
        }
    }

    public void hideUploading() {
        if (uploadingDialog != null) {
            hideDialogFragment(uploadingDialog);
        }
    }

    @Override
    public void onTopbarLeftPress() {
        onBackPressed(true);
    }

    @Override
    public boolean onBackPressed(boolean fromKey) {
        if (!ArrayUtil.isNullOrEmpty(mPictureDescriptionList)){
            mServiceInfo.setBackPic(mPictureDescriptionList.get(0).getUrl());
        }
        ServiceChangeEvent serviceChangeEvent = new ServiceChangeEvent(FormType.MAIN_PIC);
        RxBus.getDefault().send(serviceChangeEvent);
        return super.onBackPressed(fromKey);
    }

    @Override
    public void hideLoadingDialog() {
        hideLoading();
    }


    @Override
    public void addPictureDescription(PictureDescription pictureDescription) {
        mPictureDescriptionList.add(pictureDescription);
        if (TextUtils.isEmpty(mServiceInfo.getBackPic())) {
            mServiceInfo.setBackPic(mPictureDescriptionList.get(0).getUrl());
        }
        if (mAdapter!=null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_PICTURE_LIST) {
            if (resultCode == Activity.RESULT_OK) {
                ArrayList<PictureDescription> pictureDescriptionList = data.getParcelableArrayListExtra(PictureListActivity.KEY_PICTURE_LIST);
                mPictureDescriptionList.clear();
                mPictureDescriptionList.addAll(pictureDescriptionList);
                mAdapter.notifyDataSetChanged();
            }
        } else if (requestCode == REQUEST_IMAGE_SELECT) {
            if (resultCode == Activity.RESULT_OK) {
                ArrayList<String> mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                for (String path : mSelectPath) {
                    mTripEditPicPresenter.appendUploadPath(path);
                }
                mTripEditPicPresenter.uploadPicList();
                mAdapter.notifyDataSetChanged();
            }

        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }


}
